import editForm from "../form1.vue";
import examForm from "../form2.vue";
import showExam from "../form3.vue";
import { message } from "@/utils/message";
import {
  querySimulatorExamList,
  deleteSimulatorExam,
  addOrUpdateSimulatorExam
} from "@/api/simulatorexam";
import { addDialog, closeDialog } from "@/components/ReDialog";
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, onBeforeUnmount, h } from "vue";
import { emitter } from "@/utils/mitt";

export function useRole() {
  const searchForm = reactive({
    name: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      minWidth: 30,
      type: "index",
      index: (index: number) => {
        return (pagination.currentPage - 1) * pagination.pageSize + (index + 1);
      }
    },
    {
      label: "模拟卷名称",
      prop: "name",
      minWidth: 140
    },
    {
      label: "模拟考试时长",
      prop: "times",
      minWidth: 80,
      formatter: row => {
        return `${row.times}(分钟)`;
      }
    },
    {
      label: "模拟卷分数",
      prop: "totalscore",
      minWidth: 80,
      formatter: row => {
        return `${row.totalscore}分`;
      }
    },
    {
      label: "模拟得数",
      prop: "score",
      minWidth: 80,
      formatter: row => {
        return `${row.score}分`;
      }
    },
    {
      label: "创建时间",
      prop: "addtime",
      minWidth: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  function handleDelete(row) {
    deleteSimulatorExam(row)
      .then(res => {
        if (res.success) {
          message(`您删除了模拟卷名称为"${row.name}"的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message("删除数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("删除数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    querySimulatorExamList({
      name: searchForm.name,
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage
    })
      .then(res => {
        if (res.success) {
          dataList.value = res.data.list;
          pagination.total = res.data.total;
          loading.value = false;
        } else {
          message("查询数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("查询数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function newDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}模拟卷`,
      props: {
        formInline: {
          id: row?.id ?? "",
          uid: row?.uid ?? "",
          name: row?.name ?? "",
          starttime: row?.starttime ?? "",
          endtime: row?.endtime ?? "",
          times: row?.times ?? 90,
          totalscore: row?.totalscore ?? 0,
          score: row?.score ?? 0,
          del: row?.del ?? 0,
          addtime: row?.addtime ?? "",
          updatetime: row?.updatetime ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      footerButtons: [
        {
          label: "取消",
          type: "info",
          btnClick: ({ dialog: { options, index } }) => {
            closeDialog(options, index);
          }
        },
        {
          label: "确定",
          type: "success",
          btnClick: ({ dialog: { options, index } }) => {
            const FormRef = formRef.value.getRef();
            const ScoreRef = formRef.value.getScoreRef();
            console.log(JSON.stringify(ScoreRef));
            const curData = options.props.formInline as FormItemProps;
            function chores() {
              message(`您${title}了模拟卷名称为"${curData.name}"的这条数据`, {
                type: "success"
              });
              closeDialog(options, index); // 关闭弹框
              onSearch(); // 刷新表格数据
            }
            FormRef.validate(valid => {
              if (valid) {
                addOrUpdateSimulatorExam({
                  ...curData,
                  scoreList: ScoreRef
                })
                  .then(res => {
                    if (res.success) {
                      chores();
                    } else {
                      message("提交失败:" + res.errMsg, { type: "error" });
                    }
                  })
                  .catch(error => {
                    message("提交失败:" + JSON.stringify(error), {
                      type: "error"
                    });
                  });
              }
            });
          }
        }
      ]
    });
  }

  function openDialog(title = "模拟考试", row?: FormItemProps) {
    addDialog({
      title: `${title}`,
      props: {
        formInline: {
          id: row?.id ?? "",
          uid: row?.uid ?? "",
          name: row?.name ?? "",
          starttime: row?.starttime ?? "",
          endtime: row?.endtime ?? "",
          times: row?.times ?? 90,
          totalscore: row?.totalscore ?? 0,
          score: row?.score ?? 0,
          del: row?.del ?? 0,
          addtime: row?.addtime ?? "",
          updatetime: row?.updatetime ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: true,
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      headerRenderer: ({ titleId, titleClass }) => (
        // jsx 语法
        <div class="flex flex-row justify-between">
          <h4 id={titleId} class={titleClass}>
            试卷名称：{row.name}
          </h4>
          <h4 id={titleId} class={titleClass}>
            考试时长：{row.times} (分钟)
          </h4>
          <h4 id={titleId} class={titleClass}>
            试卷分数：{row.totalscore} (分)
          </h4>
        </div>
      ),
      hideFooter: true,
      contentRenderer: () => h(examForm, { ref: formRef })
    });
  }

  function showDialog(title = "查看试卷", row?: FormItemProps) {
    addDialog({
      title: `${title}`,
      props: {
        formInline: {
          id: row?.id ?? "",
          uid: row?.uid ?? "",
          name: row?.name ?? "",
          starttime: row?.starttime ?? "",
          endtime: row?.endtime ?? "",
          times: row?.times ?? 90,
          totalscore: row?.totalscore ?? 0,
          score: row?.score ?? 0,
          del: row?.del ?? 0,
          addtime: row?.addtime ?? "",
          updatetime: row?.updatetime ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: true,
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      headerRenderer: ({ titleId, titleClass }) => (
        // jsx 语法
        <div class="flex flex-row justify-between">
          <h4 id={titleId} class={titleClass}>
            试卷名称：{row.name}
          </h4>
          <h4 id={titleId} class={titleClass}>
            考试时长：{row.times} (分钟)
          </h4>
          <h4 id={titleId} class={titleClass}>
            试卷分数：{row.totalscore} (分)
          </h4>
        </div>
      ),
      hideFooter: true,
      contentRenderer: () => h(showExam, { ref: formRef })
    });
  }

  onMounted(() => {
    onSearch();
    emitter.on("onSearchEmit", () => {
      onSearch();
    });
  });

  onBeforeUnmount(() => {
    // 解绑`openPanel`公共事件，防止多次触发
    emitter.off("onSearchEmit");
  });

  return {
    searchForm,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    newDialog,
    openDialog,
    showDialog,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
